/*
Copyright (C) 2013 Matthew Netsch

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "passview.h"
#include <QApplication>
#include <QClipboard>

PassView::PassView(QAbstractItemModel *model, QLayout *parent) :
    QTableView(),
    sortproxy(new QSortFilterProxyModel())
{
    initState(model, parent);
}

PassView::~PassView()
{
    parent->removeWidget(this);
    delete sortproxy;
}

void
PassView::initState(QAbstractItemModel *model, QLayout *parent)
{
    PassView::parent = parent;

    parent->addWidget(this);
    setCornerButtonEnabled(false);
    setGridStyle(Qt::SolidLine);
    setSortingEnabled(true);
    setWordWrap(true);
    setFrameShape(QFrame::NoFrame);
    setShowGrid(true);
    setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    setDragEnabled(false);
    setDragDropMode(QAbstractItemView::NoDragDrop);
    setDropIndicatorShown(false);
    setAlternatingRowColors(true);
    setSelectionBehavior(QAbstractItemView::SelectRows);
    setSelectionMode(QAbstractItemView::SingleSelection);
    horizontalHeader()->setStretchLastSection(true);
    horizontalHeader()->setDefaultSectionSize(266);
    verticalHeader()->hide();

    sortproxy->setSourceModel(model);
    setModel(sortproxy);

    sortByColumn(0, Qt::AscendingOrder);
}

void
PassView::deleteSelected()
{
    QModelIndexList rows = selectionModel()->selectedRows();

    if (rows.isEmpty())
    {
        return;
    }

    emit rowDeleted(sortproxy->mapToSource(rows.first()).row());
}

void
PassView::changeSelectedPass(
        char *value)
{
    QModelIndexList rows = selectionModel()->selectedRows();

    if (rows.isEmpty())
    {
        return;
    }

    emit passChanged(sortproxy->mapToSource(rows.first()).row(), value);
}

void
PassView::copyPass()
{
    QModelIndexList rows = selectionModel()->selectedRows();

    if (rows.isEmpty())
    {
        return;
    }

    emit passCopied(sortproxy->mapToSource(rows.first()).row());
}
